//
//  UITableView+Chat.swift
//  EyeVisionForDoctors
//
//  Created by PMC on 2020/2/17.
//  Copyright © 2020 tao Tao. All rights reserved.
//

import UIKit

extension UITableView {
    func totalRows() -> Int {
        var i = 0
        var rowCount = 0
        while i < numberOfSections {
            rowCount += numberOfRows(inSection: i)
            i += 1
        }
        return rowCount
    }
    
    var lastIndexPath: IndexPath? {
        if totalRows() - 1 > 0 {
            return IndexPath(row: totalRows() - 1, section: 0)
        } else {
            return nil
        }
    }
    
    /// 键盘动画结束后调用
    func scrollBottomToLastRow() {
        guard let indexPath = self.lastIndexPath else { return }
        scrollToRow(at: indexPath, at: .bottom, animated: false)
    }
    
    func scrollToBottom(animated: Bool) {
        let bottomOffset = CGPoint(x: 0, y: contentSize.height - bounds.size.height)
        setContentOffset(bottomOffset, animated: animated)
    }
    
    func insertRowsAtBottom(_ rows: [IndexPath]) {
        //保证 insert row 不闪屏
        UIView.setAnimationsEnabled(false)
        CATransaction.begin()
        CATransaction.setDisableActions(true)
        self.beginUpdates()
        self.insertRows(at: rows, with: .none)
        self.endUpdates()
        self.scrollToRow(at: rows[0], at: .bottom, animated: false)
        CATransaction.commit()
        UIView.setAnimationsEnabled(true)
    }
}
